import CGlfw

public class SGWindow {
  var window: OpaquePointer?

  func createWindow() {
    guard let window = glfwCreateWindow(600, 600, "Hello World", nil, nil)
    else {
      print("Failed to open a window! I'm out!")
      glfwTerminate()
      return
    }

    self.window = window
    glfwMakeContextCurrent(window)

    //C语言回调函数采用闭包实现，闭包内不能捕获外部变量。这里使用了尾随闭包语法糖。
    glfwSetKeyCallback(self.window) { window, key, scancode, action, mods in
      print("Key = \(key)")
      if key == GLFW_KEY_ESCAPE && action == GLFW_PRESS {
        glfwSetWindowShouldClose(window, GLFW_TRUE)
      }
    }

    // Print the OpenGL version currently enabled on your machine
    let version = String(cString: glGetString(UInt32(GL_VERSION)))
    print(version)
  }

  func run() {
    glClearColor(1, 0, 0, 1)

    while glfwWindowShouldClose(self.window) == 0 {
      // Clear the screen (window background)
      glClear(UInt32(GL_COLOR_BUFFER_BIT))

      // Draw a square using the (deprecated) fixed pipeline functionality
      glColor3f(1.0, 1.0, 0.0)
      glBegin(UInt32(GL_QUADS))
      glVertex2f(-0.5, -0.5)
      glVertex2f(0.5, -0.5)
      glVertex2f(0.5, 0.5)
      glVertex2f(-0.5, 0.5)
      glEnd()

      // Swap front and back buffers for the current window
      glfwSwapBuffers(self.window)

      // Poll for events
      glfwPollEvents()
    }
  }

  deinit {
    glfwDestroyWindow(self.window)
  }
}
